package com.nuanshui.heatedloan.configBehavior;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.behavior.BehaviorAttribute;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.service.services.SafeTokenUtil;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zxh on 2016/11/19.
 */
@Repository
@BehaviorAttribute
public class SafeTokenConfigBehavior extends ConfigBehavior {

    private Logger logger = LoggerFactory.getLogger(getClass());

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserTool userTool;

	@Autowired
	private SafeTokenUtil safeTokenUtil;

    @Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserTokenService userTokenService;

    @Override
	public void doInvoke()
    {
        //是否强制登陆
        //getMap().put("mandatoryLogOn", true);
        UserAgent userAgent = (UserAgent) getServletRequest().getAttribute(GlobalParam.USER_AGENT);
        if (StringUtils.isEmpty(userAgent.getSafeToken())) {
            getMap().put("safeToken", safeTokenUtil.generateToken(userAgent.getVersion()).getKey());
        } else {
            String safeToken = userAgent.getSafeToken();
            if (!userTokenService.validSafeToken(safeToken)) {
                getMap().put("safeToken",  safeTokenUtil.generateToken(userAgent.getVersion()).getKey());
            } else {
                getMap().put("safeToken", safeToken);
            }
        }
    }

    HttpServletRequest getServletRequest() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest();
    }

}
